# 懒小子汉字教学直播工具 - 一键启动脚本
# PowerShell版本

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "   懒小子汉字教学直播工具" -ForegroundColor Yellow
Write-Host "   正在启动服务器..." -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 检查Node.js
try {
    $nodeVersion = node --version
    Write-Host "[信息] Node.js版本: $nodeVersion" -ForegroundColor Green
} catch {
    Write-Host "[错误] 未检测到Node.js，请先安装Node.js" -ForegroundColor Red
    Write-Host "下载地址: https://nodejs.org/" -ForegroundColor Yellow
    Read-Host "按回车键退出"
    exit 1
}

# 检查依赖
if (!(Test-Path "node_modules")) {
    Write-Host "[信息] 首次运行，正在安装依赖包..." -ForegroundColor Yellow
    npm install --legacy-peer-deps
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[错误] 依赖安装失败" -ForegroundColor Red
        Read-Host "按回车键退出"
        exit 1
    }
}

# 清理端口
Write-Host "[信息] 清理端口占用..." -ForegroundColor Yellow
Get-Process -Name "node" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue

# 等待端口释放
Start-Sleep -Seconds 2

# 启动服务器
Write-Host "[信息] 启动开发服务器..." -ForegroundColor Yellow
$job = Start-Job -ScriptBlock { 
    Set-Location $using:PWD
    npm run dev 
}

# 等待服务器启动
Write-Host "[信息] 等待服务器启动完成..." -ForegroundColor Yellow
do {
    Start-Sleep -Seconds 2
    $port = Get-NetTCPConnection -LocalPort 3000 -ErrorAction SilentlyContinue
} while (!$port)

# 额外等待确保完全启动
Start-Sleep -Seconds 3

# 打开浏览器
Write-Host "[信息] 打开浏览器..." -ForegroundColor Yellow
Start-Process "http://localhost:3000"

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "   启动完成！" -ForegroundColor Green
Write-Host "   浏览器地址: http://localhost:3000" -ForegroundColor Yellow
Write-Host "   按任意键关闭此窗口" -ForegroundColor Gray
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

Read-Host 